﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using FinalProject.Entities;
using FinalProject.Data.Filters;


namespace FinalProject.Data
{
    public class FinalProjectContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>()
                .HasMany(u => u.UserRoles).WithMany(r => r.Users)
                .Map(t => t.MapLeftKey("UserId")
                    .MapRightKey("UserRoleId")
                    .ToTable("UsersUserRoles"));

            modelBuilder.Entity<ChargeCategory>()
                .HasMany(c => c.ServiceTypes).WithMany(s => s.ChargeCategories)
                .Map(t => t.MapLeftKey("ChargeCategoryId")
                    .MapRightKey("ServiceTypeId")
                    .ToTable("ChargeCategoriesServiceTypes"));

            modelBuilder.Entity<TicketItem>()
                .HasMany(t => t.Colors).WithMany(c => c.TicketItems)
                .Map(t => t.MapLeftKey("TicketItemId")
                    .MapRightKey("ColorId")
                    .ToTable("TicketItemsColors"));

            modelBuilder.Entity<TicketItem>()
                .HasMany(t => t.Textures).WithMany(t => t.TicketItems)
                .Map(t => t.MapLeftKey("TicketItemId")
                    .MapRightKey("TextureId")
                    .ToTable("TicketItemsTextures"));

            modelBuilder.Entity<User>()
                .HasOptional(u => u.UserDetails)
                .WithRequired(d => d.User);
            
        }

        public DbSet<ChargeCategory> ChargeCategories { get; set; }

        public DbSet<Client> Clients { get; set; }

        public DbSet<Company> Companies { get; set; }

        public DbSet<Item> Items { get; set; }

        public DbSet<ItemColor> ItemColors { get; set; }

        public DbSet<ItemTexture> ItemTextures { get; set; }

        public DbSet<ServiceType> ServiceTypes { get; set; }

        public DbSet<Store> Stores { get; set; }

        public DbSet<Ticket> Tickets { get; set; }

        public DbSet<TicketItem> TicketItems { get; set; }

        public DbSet<User> Users { get; set; }

        public DbSet<UserDetails> UserDetails { get; set; }

        public DbSet<UserRole> UserRoles { get; set; }

        public virtual void Commit()
        {
            base.SaveChanges();
        }


        /// <summary>
        /// AppliesFilters to current context
        /// </summary>
        /// <param name="filters"></param>
        public void ApplyFilters(IList<IFilter<FinalProjectContext>> filters)
        {
            foreach (var filter in filters)
            {
                filter.DbContext = this;
                filter.Apply();
            }
        }
    }
}
